package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.hmdp.constant.MessageConstant;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    /**
     * 关注和取关操作
     * @param followId
     * @param isFollowed
     * @return
     */
    @Override
    @Transactional
    public Result follow(Long followId, Boolean isFollowed) {
        // 1.获取当前登陆用户的id
        UserDTO user = UserHolder.getUser();
        // 1.1不存在直接返回
        if(user == null){
            return Result.error(MessageConstant.USER_IS_UNLOAD);
        }
        Long userId = user.getId();
        String key = RedisConstants.FOLLOW_KEY + userId;
        if(isFollowed){
            // 2.1未关注就进行关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followId);
            follow.setCreateTime(LocalDateTime.now());
            boolean isSuccess = save(follow);
            if(isSuccess){
                // 将关注用户的id写到redis里
                stringRedisTemplate.opsForSet().add(key, followId.toString());
            }
        }else{
            // 2.2关注了就取关
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("follow_user_id", followId)
                    .eq("user_id", userId));
            if(isSuccess){
                // 将redis里的用户id删除
                stringRedisTemplate.opsForSet().remove(key, followId.toString());
            }
        }
        return Result.success();
    }

    /**
     * 判断是否已关注
     * @param followId
     * @return
     */
    @Override
    public Result queryIsFollowed(Long followId) {
        // 1.获取当前登陆用户id
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.error(MessageConstant.USER_IS_UNLOAD);
        }
        Long userId = user.getId();
        // 2.判断是否已经关注了该用户
        Integer count = query().
                eq("user_id", userId).
                eq("follow_user_id", followId).
                count();
        // 3.返回关注状态
        return Result.success(count > 0);
    }

    /**
     * 判断共同关注
     * @param followId
     */
    @Override
    public Result queryCommonFollow(Long followId) {
        // 1.根据当前登陆的用户id从redis取出关注列表
        UserDTO currentUser = UserHolder.getUser();
        if(currentUser == null){
            return Result.error(MessageConstant.USER_IS_UNLOAD);
        }
        Long userId = currentUser.getId();
        // 2.判断两个set集合的交集
        String userKey = RedisConstants.FOLLOW_KEY + userId;
        String followKey = RedisConstants.FOLLOW_KEY + followId;
        Set<String> userSet = stringRedisTemplate.opsForSet().intersect(userKey, followKey);
        // 3.解析用户数据
        if(userSet == null || userSet.isEmpty()){
            return Result.success(Collections.emptyList());
        }
        List<Long> ids = userSet.stream().map(Long::valueOf).collect(Collectors.toList());
        if(ids.isEmpty()){
            return Result.success(Collections.emptyList());
        }
        List<UserDTO> userDTOList = userService.listByIds(ids).stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4.返回
        return Result.success(userDTOList);
    }
}
